package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.ProfileActivity;
import com.starpl.mobile.android.monthunsae.november.activity.ReportActivity;
import com.starpl.mobile.android.monthunsae.november.activity.WebViewActivity;
import com.starpl.mobile.android.monthunsae.november.activity.WriteActivity;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.StarplUtil;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;
import com.starpl.mobile.android.platform.domain.CommunityArticle;


/**
 * 댓글보기 엑티비티의 리스트 핸들러
 * 
 * @author 박우람
 * @since 2011.02.22
 */
@SuppressWarnings("unused")
public class CommunityCommentListHandler extends BaseListHandler implements OnClickListener
{
	private static final String TAG = "CommentListHandler";
	private ArrayList<CommunityArticle> mList;
	private CommunityArticle mHeaderArticle;
	private String mUserId;
	private int mPostIdx;
	private int mUserIdx;
	private int mKeywordIdx;
	private boolean mHasHeaderView;

	/**
	 * 기본 생성자
	 * 
	 * @param activity
	 *            엑티비티
	 * @param userId
	 *            사용자 아이디
	 * @param userIdx
	 *            사용자 인덱스
	 * @param keywordIdx
	 *            키워드 인덱스
	 */
	public CommunityCommentListHandler(Activity activity, String userId, int userIdx, int postIdx, int keywordIdx)
	{
		super(activity);

		this.mUserId = userId;
		this.mUserIdx = userIdx;
		this.mPostIdx = postIdx;
		this.mKeywordIdx = keywordIdx;
		this.mHasHeaderView = false;
		this.mList = new ArrayList<CommunityArticle>();
	}

	@Override
	public ArrayList<?> getArrayList()
	{
		// USAGE : 사용할 리스트 객체 반환 지정
		return mList;
	}
	
	public void refreshForLast()
	{
		refresh();
		mIsWriteActivityForResult = true;
	}

	@Override
	public View getRowView(int position, View convertView)
	{
		if(convertView == null)
		{
			// USAGE : 인플레이터 활용
			convertView = inflate(R.layout.comment_default_row);
		}

		CommunityArticle article = mList.get(position);

		ImageView ivProfileImage = (ImageView) convertView.findViewById(R.id.comment_default_row_profile_image);
		TextView tvToUserName = (TextView) convertView.findViewById(R.id.comment_default_row_to_username);
		LinearLayout llReplyLayout = (LinearLayout) convertView.findViewById(R.id.comment_default_row_reply);
		TextView tvReplyCount = (TextView) convertView.findViewById(R.id.comment_default_row_reply_count);
		TextView tvContent = (TextView) convertView.findViewById(R.id.comment_default_row_content);
		ImageView ivThumbnail = (ImageView) convertView.findViewById(R.id.comment_default_row_thumbnail);
		FrameLayout flThumbnail = (FrameLayout) convertView.findViewById(R.id.comment_default_row_fl_thumbnail_expand);
		TextView tvUserName = (TextView) convertView.findViewById(R.id.comment_default_row_username);
		TextView tvDateTime = (TextView) convertView.findViewById(R.id.comment_default_row_datetime);
		ImageButton ibDelete = (ImageButton) convertView.findViewById(R.id.comment_default_row_delete_button);
		ImageButton ibReport = (ImageButton) convertView.findViewById(R.id.comment_default_row_report_button);
		ImageButton ibWrite = (ImageButton) convertView.findViewById(R.id.comment_default_row_write_button);
		ImageView ivBottomBar = (ImageView) convertView.findViewById(R.id.comment_default_row_bottom_bar);
		ImageView ivViewBar = (ImageView) convertView.findViewById(R.id.comment_default_row_view_button);
		LinearLayout llBottomLine = (LinearLayout) convertView.findViewById(R.id.comment_default_row_bottom_line);

		String profileImage = StarplUtil.addSizeTag(article.getProfileImgPath(), "60", "profile");
		ImageDownloader.download(profileImage, ivProfileImage, true);
		ivProfileImage.setOnClickListener(this);
		ivProfileImage.setTag(article);

		tvContent.setText(article.getSubject());
		tvUserName.setText(article.getStarName());
		tvDateTime.setText(article.getWrittenDate());
		ibWrite.setOnClickListener(this);
		tvUserName.setOnClickListener(this);
		tvUserName.setTag(article);

		ibWrite.setTag(article);

		// 자신의 글일 경우 삭제 버튼을 보여준다.
		if(mUserIdx == article.getUserIdx())
		{
			ibDelete.setVisibility(ImageButton.VISIBLE);
			ibDelete.setTag(article);
			ibDelete.setOnClickListener(this);
			
			ibReport.setVisibility(ImageButton.GONE);
		}
		else
		{
			ibDelete.setVisibility(ImageButton.GONE);
			
			ibReport.setVisibility(ImageButton.VISIBLE);
			ibReport.setTag(article);
			ibReport.setOnClickListener(this);
		}

		// 첫번째 데이터일 경우
		if(position == 0)
		{
			// 푸터에 글정보 추가
			mFooterView.setTag(article);

			// 긴줄글일 경우
			if(article.getPostTypeCode() != null && article.getPostTypeCode().equals("POTC20"))
			{
				ivViewBar.setVisibility(ImageView.VISIBLE);
				ivBottomBar.setVisibility(ImageView.GONE);

				ivViewBar.setOnClickListener(this);
				ivViewBar.setTag(article);
			}
			else
			{
				ivViewBar.setVisibility(ImageView.GONE);
				ivBottomBar.setVisibility(ImageView.VISIBLE);
			}

			ivBottomBar.setOnClickListener(this);
			ivBottomBar.setTag(position);
			llBottomLine.setVisibility(LinearLayout.GONE);
			convertView.setBackgroundColor(Color.parseColor("#cfcfcf"));

			// 댓글 숫자
			int replyCount = article.getReplyCount();
			if(replyCount > 0)
			{
				llReplyLayout.setVisibility(TextView.VISIBLE);
				tvReplyCount.setText("(" + article.getReplyCount() + ")");
			}
			else
			{
				llReplyLayout.setVisibility(TextView.GONE);
			}
		}
		else
		{
			llReplyLayout.setVisibility(TextView.INVISIBLE);
			convertView.setBackgroundColor(Color.parseColor("#f0f0f0"));
			ivViewBar.setVisibility(ImageView.GONE);
			ivBottomBar.setVisibility(ImageView.GONE);
			llBottomLine.setVisibility(LinearLayout.VISIBLE);
		}

		// 댓글의 댓글인 경우 대상자명 표시
		if(article.getType() == CommunityArticle.TYPE_REPLY_OF_REPLY)
		{
			tvToUserName.setVisibility(TextView.VISIBLE);
			tvToUserName.setText("To." + article.getBrotherStarName());
		}
		else
		{
			tvToUserName.setVisibility(TextView.GONE);
		}

		// 첨부 이미지
		String thumbnail = article.getPostImgPath();
		if(thumbnail != null && thumbnail.length() > 0)
		{
			thumbnail = StarplUtil.addSizeTag(article.getPostImgPath(), "66", "thumbnail");
			
			flThumbnail.setVisibility(FrameLayout.VISIBLE);
			ivThumbnail.setOnClickListener(this);
			ivThumbnail.setTag(article);
			ImageDownloader.download(thumbnail, ivThumbnail);
		}
		else
		{
			flThumbnail.setVisibility(FrameLayout.GONE);
		}

		convertView.setTag(article);

		return convertView;
	}

	@Override
	public void onRowClick(View v)
	{
		
	}

	@Override
	public void onRowClear()
	{
		mList.clear();
	}

	@Override
	public void loadContent()
	{
		// USAGE : 일반적으로 리스트를 가져오는 로직을 추가
		// USAGE : 인플레이터 활용
		final View convertView = inflate(R.layout.comment_default_row);

		HttpHandler httpHandler = new HttpHandler(mParentActivity)
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject object = (JSONObject) result;
					if(object.getString("success").equals("true"))
					{
						// 글 리스트를 처리한다.
						JSONArray articleArray = object.getJSONArray("data");

						int keywordArticleCount = articleArray.length();
						CommunityArticle communityArticle;

						for(int i = 0 ; i < keywordArticleCount ; i++)
						{
							communityArticle = new CommunityArticle((JSONObject) articleArray.get(i));
							mList.add(communityArticle);
						}

						// 헤더뷰를 생성할지 여부 결정
						if(!object.isNull("extData1") && !mHasHeaderView)
						{
							JSONObject extObject = object.getJSONObject("extData1");
							CommunityArticle article = new CommunityArticle(extObject);
							mHeaderArticle = article;

							ImageView ivProfileImage = (ImageView) convertView.findViewById(R.id.comment_default_row_profile_image);
							LinearLayout llReplyLayout = (LinearLayout) convertView.findViewById(R.id.comment_default_row_reply);
							TextView tvToUserName = (TextView) convertView.findViewById(R.id.comment_default_row_to_username);
							TextView tvContent = (TextView) convertView.findViewById(R.id.comment_default_row_content);
							ImageView ivThumbnail = (ImageView) convertView.findViewById(R.id.comment_default_row_thumbnail);
							FrameLayout flThumbnail = (FrameLayout) convertView.findViewById(R.id.comment_default_row_fl_thumbnail_expand);
							TextView tvUserName = (TextView) convertView.findViewById(R.id.comment_default_row_username);
							TextView tvDateTime = (TextView) convertView.findViewById(R.id.comment_default_row_datetime);
							ImageButton ibDelete = (ImageButton) convertView.findViewById(R.id.comment_default_row_delete_button);
							ImageButton ibReport = (ImageButton) convertView.findViewById(R.id.comment_default_row_report_button);
							ImageButton ibWrite = (ImageButton) convertView.findViewById(R.id.comment_default_row_write_button);
							ImageView ivBottomBar = (ImageView) convertView.findViewById(R.id.comment_default_row_bottom_bar);

							ImageDownloader.download(article.getProfileImgPath(), ivProfileImage, true);
							tvContent.setText(article.getSubject());
							tvUserName.setText(article.getStarName());
							tvDateTime.setText(article.getWrittenDate());

							// 사용자 프로필 이미지
							ivProfileImage.setOnClickListener(CommunityCommentListHandler.this);
							tvUserName.setOnClickListener(CommunityCommentListHandler.this);

							ivProfileImage.setTag(article);
							tvUserName.setTag(article);

							tvUserName.setTag(article);
							ibDelete.setTag(article);
							ibWrite.setTag(article);

							// 삭제 및 글쓰기
							ibDelete.setOnClickListener(CommunityCommentListHandler.this);
							ibWrite.setOnClickListener(CommunityCommentListHandler.this);

							// 자신의 글일 경우 삭제 버튼을 보여준다.
							if(mUserIdx == article.getUserIdx())
							{
								ibDelete.setVisibility(ImageButton.VISIBLE);
								ibDelete.setTag(article);
								ibDelete.setOnClickListener(CommunityCommentListHandler.this);
								
								ibReport.setVisibility(ImageButton.GONE);
							}
							else
							{
								ibDelete.setVisibility(ImageButton.GONE);
								
								ibReport.setVisibility(ImageButton.VISIBLE);
								ibReport.setTag(article);
								ibReport.setOnClickListener(CommunityCommentListHandler.this);
							}

							// 댓글의 댓글인 경우 To를 보여준다.
							if(article.getUserIdx() != article.getBrotherUserIdx())
							{
								tvToUserName.setVisibility(TextView.VISIBLE);
								tvToUserName.setText("To." + article.getBrotherStarName());
							}

							llReplyLayout.setVisibility(TextView.INVISIBLE);
							convertView.setBackgroundColor(Color.parseColor("#ffffff"));
							ivBottomBar.setVisibility(ImageView.GONE);

							// 첨부 이미지
							String thumbnail = article.getPostImgPath();
							if(thumbnail != null && thumbnail.length() > 0)
							{
								thumbnail = StarplUtil.addSizeTag(article.getPostImgPath(), "66", "thumbnail");
								flThumbnail.setVisibility(FrameLayout.VISIBLE);
								ivThumbnail.setOnClickListener(CommunityCommentListHandler.this);
								ivThumbnail.setTag(article);
								ImageDownloader.download(thumbnail, ivThumbnail);
							}
							else
							{
								flThumbnail.setVisibility(FrameLayout.GONE);
							}

							// USAGE : 헤더뷰를 수동으로 추가한다.
							showHeaderView(convertView);
							mHasHeaderView = true;
						}
					}

					// USAGE : 어댑터를 붙인다. 실제로 데이터와 리스트뷰가 연결된다.
					setAdapter();

					notifyDataSetChanged();
					
					if(mIsWriteActivityForResult)
					{
						mIsWriteActivityForResult = false;
						mListView.setSelection(mListView.getCount()-1);
					}
					
				}
				catch(JSONException e)
				{
					e.printStackTrace();
				}
			}
		};

		StarplCommand.getPostReply(httpHandler, mUserId, mPostIdx);
	}

	@Override
	public View getFooterView()
	{
		// USAGE : 푸터뷰를 반환
		View vFooterView = new ImageButton(mParentActivity);
		vFooterView.setId(R.drawable.button_comment_bottom);
		vFooterView.setBackgroundResource(R.drawable.button_comment_bottom);
		vFooterView.setOnClickListener(this);
		return vFooterView;
	}

	@Override
	public void onClick(final View view)
	{
		final CommunityArticle article = (CommunityArticle) view.getTag();
		Bundle extras;
		switch(view.getId())
		{
		// 사용자 프로필
		case R.id.comment_default_row_profile_image:
		case R.id.comment_default_row_username:
			extras = new Bundle();
			extras.putString("userId", article.getUserId());
			extras.putString("nickname", article.getStarName());
			extras.putInt("userIdx", article.getUserIdx());

			getNewActivity()
				.setBundle(extras)
				.setTargetActivity(ProfileActivity.class)
				.show();
			break;

		// 글 삭제
		case R.id.comment_default_row_delete_button:
			
			final HttpHandler deletePostHandler = new HttpHandler(mParentActivity, "글 삭제 중 입니다")
			{
				@Override
				public void didSucceed(Object result)
				{
					mParentActivity.setResult(Activity.RESULT_OK);
					if(article == mList.get(0) || (mHeaderArticle != null && article.getPostIdx() == mHeaderArticle.getPostIdx()))
					{
						new AlertDialog.Builder(mParentActivity)
						.setTitle(BaseApplication.getConfigPersistent("appsName"))
						.setMessage("글을 삭제했습니다")
						.setCancelable(false)
						.setPositiveButton("확인", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								dialog.dismiss();
								mParentActivity.finish();
							}
						})
						.show();
					}
					else
					{
						refresh();
					}
				}
			};
			
			new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage("정말 삭제하시겠습니까?")
			.setPositiveButton("확인", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
					StarplCommand.deleteReply(deletePostHandler, userInfo.getUserId(), article.getPostIdx());
					dialog.dismiss();
				}
			})
			.setNegativeButton("취소", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
				}
			})
			.show();
			

			break;

		// 댓글쓰기
		case R.id.comment_default_row_write_button:
		case R.drawable.button_comment_bottom:
			extras = new Bundle();
			extras.putInt("postIdx", article.getPostIdx());
			extras.putString("rcvStarName", article.getStarName());
			extras.putInt("type", WriteActivity.TYPE_REPLY);
			extras.putInt("keywordIdx", mKeywordIdx);

			getNewActivity()
				.setTargetActivity(WriteActivity.class)
				.setBundle(extras)
				.setRequestCode(17)
				.show();
			break;

		// 첨부 썸네일 이미지 보기
		case R.id.comment_default_row_thumbnail:
			extras = new Bundle();
			extras.putString("title", "사진보기");
			extras.putString("url", article.getPostImgPath());

			getNewActivity().setBundle(extras).setTargetActivity(WebViewActivity.class).show();
			break;
			
		// 긴줄글 보기
		case R.id.comment_default_row_view_button:
			extras = new Bundle();
			extras.putString("title", "내용보기");
			extras.putInt("postIdx", article.getPostIdx());
			
			getNewActivity()
				.setBundle(extras)
				.setTargetActivity(WebViewActivity.class)
				.show();
			break;
			
		// 신고하기
		case R.id.comment_default_row_report_button:
			extras = new Bundle();
			extras.putInt("postIdx", article.getPostIdx());
			
			getNewActivity()
				.setTargetActivity(ReportActivity.class)
				.setBundle(extras)
				.show();
			break;
		}
	}

	@Override
	public void onInit()
	{
		// USAGE : 푸터뷰를 붙인다.
		showFooterView();

		// USAGE : 컨텐츠 수동 호출
		loadContent();
	}
}